package com.ruoyi.web.controller.module.order;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MyUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerUserService;
import com.ruoyi.market.domain.ConfigGlobal;
import com.ruoyi.market.domain.ConfigPay;
import com.ruoyi.market.domain.ConfigProgram;
import com.ruoyi.market.service.IConfigGlobalService;
import com.ruoyi.market.service.IConfigPayService;
import com.ruoyi.market.service.IConfigProgramService;
import com.ruoyi.order.domain.OrderGift;
import com.ruoyi.order.service.IOrderGiftService;
import com.ruoyi.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 礼物订单信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/order/gift")
public class OrderGiftController extends BaseController
{
    @Autowired
    private IOrderGiftService orderGiftService;

    @Autowired
    private ICustomerUserService customerUserService;

    @Autowired
    private IConfigGlobalService configGlobalService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IConfigPayService configPayService;

    @Autowired
    private IConfigProgramService configProgramService;

    /**
     * 获取礼物订单列表
     */
    @PostMapping("/orderGiftList")
    public TableDataInfo orderGiftList(@RequestBody OrderGift orderGift, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGift.setShopId(shopId);
        }
        startPageByPost();
        List<OrderGift> list = orderGiftService.selectOrderGiftList(orderGift);
        return getDataTable(list);
    }

    /**
     * 获取礼物订单列表 - 联合数据
     */
    @PostMapping("/orderGiftUnionList")
    public AjaxResult orderGiftUnionList(HttpServletRequest request){
        AjaxResult ajax = AjaxResult.success();
        OrderGift orderGift_top = new OrderGift();
        OrderGift orderGift_normal = new OrderGift();
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGift_top.setShopId(shopId);
            orderGift_normal.setShopId(shopId);
        }
        ConfigGlobal sysConfigGlobal = configGlobalService.selectConfigGlobalByShopId(shopId);
        if(sysConfigGlobal != null && sysConfigGlobal.getGiftShowTopStatus().equals(UserConstants.YES)){
            // 置顶告白专区是否显示 Y-是 N-否 默认 N 开启后显示最近N天内打赏金额最高的3个打赏
            PageHelper.startPage(1, 3).setReasonable(true);
            // desc为降序，asc为升序  出错的原因 同时使用 PageHelper.orderBy("initAmount desc") 和 startPageByPost();
            PageHelper.orderBy("actual_amount desc");
            Map<String, Object> params_top = new HashMap<>();
            String endTime = MyUtils.dateToStrLong(new Date());
            int giftRecentDay = 7;
            String dayStr = configService.selectConfigByKey("app.gift.recent.day");
            if(dayStr != null && !dayStr.equals("")){
                try {
                    giftRecentDay = Integer.parseInt(dayStr);
                } catch (NumberFormatException e) {
                    System.out.println("字符串不是有效的整数格式");
                }
            }
            String beginTime = MyUtils.getBeforeDay(endTime, giftRecentDay);
            params_top.put("beginTime", beginTime);
            params_top.put("endTime", endTime);
            orderGift_top.setParams(params_top);
            orderGift_top.setPayStatus(UserConstants.PAY_STATUS_PAID);

            List<OrderGift> topList = orderGiftService.selectOrderGiftList(orderGift_top);
            ajax.put("topList", topList);
            ajax.put("giftShowTopStatus", "Y");
        }else{
            ajax.put("giftShowTopStatus", "N");
        }
        ajax.put("giftShowTimeStatus", sysConfigGlobal.getGiftShowTimeStatus());

        PageHelper.clearPage();

        int pageNum = 10;
        BigDecimal giftShowMin = new BigDecimal(0);
        Map<String, Object> params_normal = new HashMap<>();
        if(sysConfigGlobal != null){
            pageNum = sysConfigGlobal.getGiftShowCount();
            giftShowMin = sysConfigGlobal.getGiftShowMin();
        }
        params_normal.put("minAmount", giftShowMin);
        orderGift_normal.setParams(params_normal);
        orderGift_normal.setPayStatus(UserConstants.PAY_STATUS_PAID);
        PageHelper.startPage(1, pageNum).setReasonable(true);
        PageHelper.orderBy("create_time desc");

        List<OrderGift> giftList = orderGiftService.selectOrderGiftList(orderGift_normal);
        ajax.put("giftList", giftList);
        return ajax;
    }

    @Log(title = "礼物订单管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('order:gift:export')")
    @PostMapping("/orderGiftExport")
    public void export(HttpServletResponse response, OrderGift orderGift)
    {
        List<OrderGift> list = orderGiftService.selectOrderGiftList(orderGift);
        ExcelUtil<OrderGift> util = new ExcelUtil<OrderGift>(OrderGift.class);
        util.exportExcel(response, list, "礼物订单数据");
    }

    /**
     * 根据礼物订单编号获取详细信息
     */
    @GetMapping(value = { "/", "/{orderNo}" })
    public AjaxResult getInfo(@PathVariable(value = "orderNo", required = false) String orderNo)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(orderNo))
        {
            OrderGift orderGift = orderGiftService.selectOrderGiftByOrderNo(orderNo);
            ajax.put(AjaxResult.DATA_TAG, orderGift);
        }
        return ajax;
    }

    /**
     * 新增礼物订单
     */
    @PostMapping("/orderGiftCreate")
    public AjaxResult orderGiftCreate(@Validated @RequestBody OrderGift orderGift, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            orderGift.setShopId(shopId);
        }
        Long userId = SecurityUtils.getUserId();
        CustomerUser cu = customerUserService.selectUserById(userId);
        customerUserService.checkUserAllowed(cu);
        AjaxResult ajax = AjaxResult.success();

        ConfigPay configPay = configPayService.selectConfigPayByShopId(shopId);
        ConfigProgram configProgram = configProgramService.selectConfigProgramByShopId(shopId);
        ajax.put(AjaxResult.DATA_TAG, orderGiftService.insertOrderGift(orderGift));
        ajax.put("configPay", configPay);
        ajax.put("configProgram", configProgram);
        return ajax;
    }

    /**
     * 修改礼物订单
     */
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody OrderGift orderGift)
    {
        return toAjax(orderGiftService.updateOrderGift(orderGift));
    }

    /**
     * 删除礼物订单
     */
    @PreAuthorize("@ss.hasPermi('order:gift:remove')")
    @Log(title = "礼物订单管理 - 删除礼物订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderNos}")
    public AjaxResult remove(@PathVariable String[] orderNos)
    {
        return toAjax(orderGiftService.deleteOrderGiftByOrderNos(orderNos));
    }
}
